﻿using System.Configuration;
using System.Reflection;
using System.IO;

namespace CodeStash.Common.Helpers
{
    public static class ConfigurationSettings
    {
        private static Configuration configuration;

        public static bool EncryptionEnabled
        {
            get
            {
                string returnValue = RetrieveSetting("EncryptionEnabled");
                if (string.IsNullOrWhiteSpace(returnValue))
                    return false;

                return bool.Parse(returnValue);
            }
        }

        /// <summary>
        /// Gets the RESTful service address.
        /// </summary>
        public static string RestAddress
        {
            get
            {
                return RetrieveSetting("RestAddress");
            }
        }

        /// <summary>
        /// Gets the REST CodeSnippet service address.
        /// </summary>
        public static string CodeSnippetAddress
        {
            get
            {
                return RetrieveSetting("CodeSnippet");
            }
        }

        /// <summary>
        /// Gets the address of the CodeStash website.
        /// </summary>
        public static string CodeStashWebAddress
        {
            get
            {
                return RetrieveSetting("CodeStashWebAddress");
            }
        }

        /// <summary>
        /// Get the configuration if it has not previously been opened.
        /// </summary>
        private static void GetConfiguration()
        {
            if (configuration != null) return;
            string location = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "CodeStash.Addin.Core.dll");
            configuration = ConfigurationManager.OpenExeConfiguration(location);
        }

        /// <summary>
        /// Get the setting from the underlying configuration file.
        /// </summary>
        /// <param name="setting">The setting to read from the file.</param>
        /// <returns>The setting.</returns>
        private static string RetrieveSetting(string setting)
        {
            string value = ConfigurationManager.AppSettings[setting];
            if (string.IsNullOrWhiteSpace(value))
            {
                GetConfiguration();
                KeyValueConfigurationElement ret = configuration.AppSettings.Settings[setting];
                if (ret != null)
                {
                    value = ret.Value;
                }
            }

            return value;
        }
    }
}